// src/services/cacheService.ts
import AsyncStorage from '@react-native-async-storage/async-storage';

interface CacheItem<T> {
  data: T;
  timestamp: number;
  expiresAt?: number;
}

interface CacheOptions {
  ttl?: number; // Time to live in seconds
  encrypt?: boolean;
}

class CacheService {
  private prefix = 'cache_';

  // 设置缓存
  async set<T>(key: string, data: T, options?: CacheOptions): Promise<void> {
    const cacheKey = this.getCacheKey(key);
    const timestamp = Date.now();
    const expiresAt = options?.ttl ? timestamp + (options.ttl * 1000) : undefined;

    const cacheItem: CacheItem<T> = {
      data,
      timestamp,
      expiresAt,
    };

    const value = JSON.stringify(cacheItem);

    if (options?.encrypt) {
      // 这里可以添加加密逻辑
    }

    await AsyncStorage.setItem(cacheKey, value);
  }

  // 获取缓存
  async get<T>(key: string): Promise<T | null> {
    const cacheKey = this.getCacheKey(key);

    try {
      const value = await AsyncStorage.getItem(cacheKey);

      if (!value) {
        return null;
      }

      const cacheItem: CacheItem<T> = JSON.parse(value);

      // 检查是否过期
      if (cacheItem.expiresAt && Date.now() > cacheItem.expiresAt) {
        await this.remove(key);
        return null;
      }

      return cacheItem.data;
    } catch (error) {
      console.error('Cache get error:', error);
      return null;
    }
  }

  // 删除缓存
  async remove(key: string): Promise<void> {
    const cacheKey = this.getCacheKey(key);
    await AsyncStorage.removeItem(cacheKey);
  }

  // 清除所有缓存
  async clear(): Promise<void> {
    const keys = await AsyncStorage.getAllKeys();
    const cacheKeys = keys.filter(key => key.startsWith(this.prefix));
    await AsyncStorage.multiRemove(cacheKeys);
  }

  // 清除过期缓存
  async clearExpired(): Promise<void> {
    const keys = await AsyncStorage.getAllKeys();
    const cacheKeys = keys.filter(key => key.startsWith(this.prefix));

    for (const key of cacheKeys) {
      try {
        const value = await AsyncStorage.getItem(key);
        if (value) {
          const cacheItem: CacheItem<any> = JSON.parse(value);
          if (cacheItem.expiresAt && Date.now() > cacheItem.expiresAt) {
            await AsyncStorage.removeItem(key);
          }
        }
      } catch (error) {
        console.error('Clear expired cache error:', error);
      }
    }
  }

  // 获取缓存大小
  async getSize(): Promise<number> {
    const keys = await AsyncStorage.getAllKeys();
    const cacheKeys = keys.filter(key => key.startsWith(this.prefix));

    let totalSize = 0;
    for (const key of cacheKeys) {
      const value = await AsyncStorage.getItem(key);
      if (value) {
        totalSize += value.length;
      }
    }

    return totalSize;
  }

  // 批量设置
  async setMultiple(items: Array<{ key: string; data: any; options?: CacheOptions }>): Promise<void> {
    const pairs = items.map(item => {
      const cacheKey = this.getCacheKey(item.key);
      const timestamp = Date.now();
      const expiresAt = item.options?.ttl ? timestamp + (item.options.ttl * 1000) : undefined;

      const cacheItem: CacheItem<any> = {
        data: item.data,
        timestamp,
        expiresAt,
      };

      return [cacheKey, JSON.stringify(cacheItem)] as const;
    });

    await AsyncStorage.multiSet(pairs);
  }

  // 批量获取
  async getMultiple<T>(keys: string[]): Promise<Map<string, T | null>> {
    const cacheKeys = keys.map(key => this.getCacheKey(key));
    const pairs = await AsyncStorage.multiGet(cacheKeys);

    const result = new Map<string, T | null>();

    for (let i = 0; i < keys.length; i++) {
      const key = keys[i];
      const value = pairs[i][1];

      if (value) {
        try {
          const cacheItem: CacheItem<T> = JSON.parse(value);

          // 检查是否过期
          if (cacheItem.expiresAt && Date.now() > cacheItem.expiresAt) {
            result.set(key, null);
            await this.remove(key);
          } else {
            result.set(key, cacheItem.data);
          }
        } catch (error) {
          result.set(key, null);
        }
      } else {
        result.set(key, null);
      }
    }

    return result;
  }

  // 检查缓存是否存在
  async has(key: string): Promise<boolean> {
    const value = await this.get(key);
    return value !== null;
  }

  private getCacheKey(key: string): string {
    return `${this.prefix}${key}`;
  }
}

export default new CacheService();